package com.zmc.admin.controller.system;

import com.zmc.admin.infrastructure.bean.vo.user.SysUserProfileVo;
import com.zmc.admin.infrastructure.constant.ErrorCodeConstants;
import com.zmc.admin.infrastructure.entity.SysUserEntity;
import com.zmc.admin.infrastructure.service.SysUserService;
import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.config.SysConfig;
import com.zmc.common.domain.vo.user.UserInfo;
import com.zmc.common.enums.RequestSourceEnum;
import com.zmc.common.exception.base.WebDisplayException;
import com.zmc.common.utils.MD5Utils;
import com.zmc.common.utils.R;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.file.FileUploadUtils;
import com.zmc.common.utils.file.MimeTypeUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 * @author zmc
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private AuthTokenService authTokenService;

    /**
     * 个人信息
     */
    @PostMapping("/info")
    public R profile() {
        UserInfo userInfo = authTokenService.getUserInfo();
        String username = userInfo.getUsername();
        SysUserEntity user = userService.getById(userInfo.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("roleGroup", userService.selectUserRoleGroup(username));
        map.put("postGroup", userService.selectUserPostGroup(username));
        return R.ok(user).put(map);
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R updateProfile(@RequestBody SysUserEntity user) {
        UserInfo userInfo = authTokenService.getUserInfo();
        SysUserEntity currentUser = userService.getById(userInfo.getUserId());
        currentUser.setUserName(user.getUserName());
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhonenumber(user.getPhonenumber());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getUserName()) && !userService.checkUserNameUnique(currentUser)) {
            throw new WebDisplayException(ErrorCodeConstants.USERNAME_USED_EXCEPTION);
        }
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
            throw new WebDisplayException(ErrorCodeConstants.PHONE_USED_EXCEPTION);
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            throw new WebDisplayException(ErrorCodeConstants.EMAIL_USED_EXCEPTION);
        }
        // 更新缓存用户信息
        authTokenService.setUserInfo(userInfo);
        return R.ok();
    }

    /**
     * 重置密码
     */
    @PostMapping("/updatePwd")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R updatePwd(@Validated @RequestBody SysUserProfileVo vo) {
        String newPassword = vo.getNewPassword();
        String oldPassword = vo.getOldPassword();
        if (newPassword.equals(oldPassword)) {
            throw new WebDisplayException(ErrorCodeConstants.USER_OLD_NEW_PASSWORD_SAME_EXCEPTION);
        }
        SysUserEntity user = userService.getById(authTokenService.getUserInfo().getUserId());
        String password = user.getPassword();
        if (MD5Utils.verify(oldPassword, password)) {
            throw new WebDisplayException(ErrorCodeConstants.USER_OLD_PASSWORD_ERROR_EXCEPTION);
        }
        String salt = IdUtils.fastUUID().substring(0, 16);
        user.setPassword(MD5Utils.encrypt(newPassword, salt));
        user.setSalt(salt);
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public R avatar(@RequestBody MultipartFile avatarfile) throws Exception {
        if (!avatarfile.isEmpty()) {
            SysUserEntity user = userService.getById(authTokenService.getUserInfo().getUserId());
            String avatar = FileUploadUtils.upload(SysConfig.getAvatarPath(), avatarfile, MimeTypeUtils.IMAGE_EXTENSION);
            user.setAvatar(avatar);
            userService.updateById(user);
            return R.ok().put("imgUrl", avatar);
        }
        return R.error("上传图片异常，请联系管理员");
    }
}
